#include <string>
 #include <sys/socket.h>
 #include <netinet/in.h>
 #include <cstring>
 #include <arpa/inet.h>
 #include <iostream>
 #include <unistd.h>
 #include <sys/wait.h>
 #include <pthread.h>
#include "protocol.hpp"

using namespace std;
using namespace Protocol;

class TcpServer
{
    static void Service(int fd, struct sockaddr_in& peer)
    {
        char buffer[1024];
        string s;
        while(1)
        {
            int n= read(fd, buffer, sizeof(buffer)-1);
            if(n> 0)
            {
                buffer[n]= 0;
                s+= buffer;

                string tmp;

                if(DeLenHeader(s, &tmp))
                {
                    Request req;
                    req.DeSerialize(tmp);


                    int result;
                    switch(req._op)
                    {
                    case '+':
                        result= req._x+ req._y;
                        break;
                    case '-':
                        result= req._x- req._y;
                        break;
                    case '/':
                        result= req._x/ req._y;
                        break;
                    case '*':
                        result= req._x* req._y;
                        break;
                    }
                    
                    Response rsp(result, 0);

                    string sen= rsp.Serialize();
                    EnLenHeader(sen);

                    write(fd, sen.c_str(), sen.size());
                }
                else
                {
                    //数据还不够，啥也不干
                }
            }
            else if(n== 0)
            {
                cout<<"连接断开，客户端为："<<inet_ntoa(peer.sin_addr)<<" "<<ntohs(peer.sin_port)<<endl;
                break;
            }
        }
    }

    struct ThreadData
    {
        int _fd;
        struct sockaddr_in _peer;

        ThreadData(int fd, struct sockaddr_in peer)
        :_fd(fd)
        ,_peer(peer)
        {}
    };

    static void* ExecuteThread(void* arg)
    {
        pthread_detach(pthread_self());//分离线程，到时候线程函数执行完直接释放tcb
        ThreadData* p= (ThreadData*)arg;
        Service(p->_fd, p->_peer);
        close(p->_fd);
        delete p;
        return nullptr;   //BUG----如果线程启动函数执行完毕却没有返回值，那就会出现非法指令的情况
    }

    void ConnectionHandle(int fd, struct sockaddr_in& peer)
    {
        pthread_t t;
        ThreadData* data= new ThreadData(fd, peer);
        pthread_create(&t, nullptr, ExecuteThread, data);
    }
public:
    TcpServer(int port)
    :_port(port)
    {}

    void Init()
    {
        _sockfd= socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);

        struct sockaddr_in local;
        memset(&local, 0, sizeof(local));
        local.sin_family= AF_INET;
        local.sin_addr.s_addr= htonl(INADDR_ANY);
        local.sin_port= htons(_port);

        int opt=1;
        setsockopt(_sockfd, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));
        bind(_sockfd, (struct sockaddr*)&local, sizeof(local));

        listen(_sockfd, 8);
    }

   

    void Start()
    {
        _isrunning= true;

        while(_isrunning)
        {
            struct sockaddr_in peer;
            socklen_t len= sizeof(peer);
            int fd= accept(_sockfd, (struct sockaddr*)&peer, &len);

            cout<<"client connected: "<<inet_ntoa(peer.sin_addr)<<" "<<ntohs(peer.sin_port)<<endl;
            ConnectionHandle(fd, peer);
        }
    }

private:
    int _port;
    int _sockfd;
    bool _isrunning;
};


int main()
{
    TcpServer server(8888);
    server.Init();
    server.Start();

    return 0;
}